#define _GNU_SOURCE
#include <pthread.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/time.h>
#include <stdlib.h>

// 线程函数
void *sum_sqr_thread_fun(void *arg)
{
    int num = *(int *)arg; // 得到主线程传来的数据
    int *result = malloc(sizeof(int));
    *result = num * num;
    sleep(1);

    // return result;
    pthread_exit(result);
}

int main(int argc, char const *argv[])
{
    int items[5] = {1, 2, 3, 4, 5};
    int sqrs[5], sum;
    struct timeval start, end;
    gettimeofday(&start, NULL);
    pthread_t threads[5];
    for (int i = 0; i < 5; i++)
    {
        pthread_create(&threads[i], NULL, sum_sqr_thread_fun, &items[i]);
    }

    // 等待所有线程执行完毕
    for (int i = 0; i < 5; i++)
    {
        void *result;
        //pthread_join函数会阻塞主线程，直到子线程执行完毕 参数一为线程id 参数二为子线程的返回值
        pthread_join(threads[i], &result);
        sqrs[i] = *(int *)result;
        free(result);
    }
    gettimeofday(&end, NULL);
    printf("time = %ld\n", end.tv_sec - start.tv_sec);
    for (int i = 0; i < 5; i++)
    {
        sum += sqrs[i];
    }
    printf("sum = %d\n", sum);
    return 0;
}
